<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="检验计划单号" prop="planId">
        <el-input
          v-model="queryParams.planId"
          placeholder="请输入检验计划单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="收料通知单号" prop="receiveId">
        <el-input
          v-model="queryParams.receiveId"
          placeholder="请输入收料通知单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采购订单号" prop="poId">
        <el-input
          v-model="queryParams.poId"
          placeholder="请输入采购订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="存货编码" prop="itemId">
        <el-input
          v-model="queryParams.itemId"
          placeholder="请输入存货编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="批次号" prop="batch">
        <el-input
          v-model="queryParams.batch"
          placeholder="请输入批次号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['purchase:plan:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['purchase:plan:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['purchase:plan:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['purchase:plan:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="planList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="检验计划ID" align="center" prop="id" />
      <el-table-column label="检验计划单号" align="center" prop="planId" />
      <el-table-column label="收料通知单号" align="center" prop="receiveId" />
      <el-table-column label="采购订单号" align="center" prop="poId" />
      <el-table-column label="存货编码" align="center" prop="itemId" />
      <el-table-column label="存货名称" align="center" prop="itemName" />
      <el-table-column label="规格型号" align="center" prop="spec" />
      <el-table-column label="批次号" align="center" prop="batch" />
      <el-table-column label="供应商编码" align="center" prop="vendorId" />
      <el-table-column label="检验状态：0-待检验，1-检验中，2-已完成" align="center" prop="inspectionStatus" />
      <el-table-column label="检验状态" align="center" prop="inspectionStatus">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.inspectionStatus === 0" type="warning">待检验</el-tag>
          <el-tag v-else-if="scope.row.inspectionStatus === 1" type="primary">检验中</el-tag>
          <el-tag v-else type="success">已检验</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="检验结果" align="center" prop="inspectionResult">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.inspectionResult === 0" type="info">未检验</el-tag>
          <el-tag v-else-if="scope.row.inspectionResult === 1" type="danger">不合格</el-tag>
          <el-tag v-else type="success">合格</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="拒收状态" align="center" prop="rejectStatus">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.rejectStatus === 0" type="info">默认</el-tag>
          <el-tag v-else-if="scope.row.rejectStatus === 1" type="danger">拒收</el-tag>
          <el-tag v-else type="success">未拒收</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleInspect(scope.row)"
            v-hasPermi="['purchase:inspectionPlan:edit']"
            v-if="scope.row.inspectionStatus !== 2"
          >检验</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['purchase:inspectionPlan:query']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['purchase:plan:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['purchase:plan:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 检验对话框 -->
    <el-dialog :title="'检验 - ' + currentPlan.planId" :visible.sync="inspectOpen" width="1400px" append-to-body>
      <el-form ref="inspectForm" :model="inspectForm" :rules="inspectRules" label-width="120px">
        <!-- 基本信息 -->

              <el-form-item label="存货编码">{{ currentPlan.itemId }}</el-form-item>
              <el-form-item label="存货名称">{{ currentPlan.itemName }}</el-form-item>
              <el-form-item label="规格型号">{{ currentPlan.spec }}</el-form-item>
              <el-form-item label="批次">{{ currentPlan.batch }}</el-form-item>
              <el-form-item label="检验人" prop="inspector">
                <el-input v-model="inspectForm.inspector" placeholder="请输入检验人" />
              </el-form-item>
              <el-form-item label="实际抽检数量" prop="actualQuantity">
                    <el-input-number
                      v-model="inspectForm.actualQuantity"
                      :min="0"
                      placeholder="请输入抽检数量"
                      style="width: 100%;"
                     />
              </el-form-item>
        <el-form-item label="不合格数量" prop="rejectQuantity">
          <el-input-number
            v-model="inspectForm.rejectQuantity"
            :min="0"
            placeholder="自动计算"
            style="width: 100%;"
            readonly
          />
        </el-form-item>
        <el-form-item label="合格数量" prop="qualifiedQuantity">
          <el-input-number
            v-model="inspectForm.qualifiedQuantity"
            :min="0"
            placeholder="自动计算"
            style="width: 100%;"
            readonly
          />
        </el-form-item>


        <el-form-item label="检验结果" prop="inspectionResult">
          <el-radio-group v-model="inspectForm.inspectionResult">
            <el-radio :label="2">合格</el-radio>
            <el-radio :label="1">不合格</el-radio>
          </el-radio-group>
        </el-form-item>


        <el-form-item label="是否拒收" prop="rejectStatus">
          <el-radio-group v-model="inspectForm.isRejected">
            <el-radio :label="2">收货</el-radio>
            <el-radio :label="1">拒收</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>


      <!-- 不合格区域 -->
      <el-card header="不合格区域" style="margin-bottom: 20px;">
        <div style="margin-bottom: 10px;">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddRejection">新增</el-button>
        </div>
        <el-table :data="inspectForm.rejectionRecords" border>
          <el-table-column type="index" width="50" label="序号" />
          <el-table-column prop="rejectionReason" label="不合格原因">
            <template slot-scope="scope">
              <el-select v-model="scope.row.rejectionReason" placeholder="请选择不合格原因" style="width: 100%;">
                <el-option label="卡扣不良" value="卡扣不良" />
                <el-option label="拉拔力" value="拉拔力" />
                <el-option label="钻孔不良" value="钻孔不良" />
                <el-option label="尺寸偏差" value="尺寸偏差" />
                <el-option label="外观缺陷" value="外观缺陷" />
                <el-option label="其他" value="其他" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="rejectionQuantity" label="数量">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.rejectionQuantity"
                style="width: 100%;"
              />
            </template>
          </el-table-column>
          <el-table-column prop="handlingMethod" label="处理方式">
            <template slot-scope="scope">
              <el-input v-model="scope.row.handlingMethod" placeholder="请输入处理方式" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleRemoveRejection(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 按指标检验区域 -->
      <el-card header="按指标检验区域">
        <div style="margin-bottom: 10px;">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddInspectionItem">新增</el-button>
        </div>
        <el-table :data="inspectForm.inspectionResults" border>
          <el-table-column type="index" width="50" label="序号" />
          <el-table-column prop="itemName" label="检验项目" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.itemName" placeholder="请输入检验项目" />
            </template>
          </el-table-column>
          <el-table-column prop="inspectionIndex" label="检验指标" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.inspectionIndex" placeholder="请输入检验指标" />
            </template>
          </el-table-column>
          <el-table-column prop="inspectionMethod" label="检验方法" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.inspectionMethod" placeholder="请输入检验方法" />
            </template>
          </el-table-column>
          <el-table-column prop="standardValue" label="标准值" width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.standardValue" placeholder="标准值" />
            </template>
          </el-table-column>
          <el-table-column prop="upperLimit" label="上限值" width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.upperLimit" placeholder="上限值" />
            </template>
          </el-table-column>
          <el-table-column prop="lowerLimit" label="下限值" width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.lowerLimit" placeholder="下限值" />
            </template>
          </el-table-column>
          <el-table-column label="检验数据" width="500">
            <template slot-scope="scope">
              <el-row :gutter="5">
                <el-col :span="4">
                  <el-input v-model="scope.row.testValue1" placeholder="数据1" size="mini" />
                </el-col>
                <el-col :span="4">
                  <el-input v-model="scope.row.testValue2" placeholder="数据2" size="mini" />
                </el-col>
                <el-col :span="4">
                  <el-input v-model="scope.row.testValue3" placeholder="数据3" size="mini" />
                </el-col>
                <el-col :span="4">
                  <el-input v-model="scope.row.testValue4" placeholder="数据4" size="mini" />
                </el-col>
                <el-col :span="4">
                  <el-input v-model="scope.row.testValue5" placeholder="数据5" size="mini" />
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleRemoveInspectionItem(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <!-- 备注 -->
      <el-form-item label="备注" prop="remark">
        <el-input v-model="inspectForm.remark" type="textarea" placeholder="请输入备注" />
      </el-form-item>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitInspectForm" :loading="inspectLoading">确 定</el-button>
        <el-button @click="inspectOpen = false">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { listPlan, getPlan, delPlan, addPlan, updatePlan } from "@/api/purchase/plan"

export default {
  name: "Plan",
  data() {
    return {
      // 检验表单
      inspectForm: {
        id: null,
        planId: '',
        actualQuantity: 0,
        rejectQuantity: 0,
        qualifiedQuantity: 0,
        inspector: '检验员王经理',
        inspectionResult: 2,
        isRejected: 2,
        remark: '',
        rejectionRecords: [],
        inspectionResults: []
      },
      // 检验对话框显示控制
      inspectOpen: false,
      viewOpen: false,
      // 当前检验计划
      currentPlan: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 收料检验计划表格数据
      planList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        planId: null,
        receiveId: null,
        poId: null,
        itemId: null,
        batch: null,
        vendorId: null,
        inspectionStatus: null,
        inspector: null,
        inspectionResult: null,
        actualQuantity: null,
        rejectQuantity: null,
        qualifiedQuantity: null,
        isRejected: null,
        createdAt: null,
        createdPerson: null,
        updatedAt: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        planId: [
          { required: true, message: "检验计划单号不能为空", trigger: "blur" }
        ],
        receiveId: [
          { required: true, message: "收料通知单号不能为空", trigger: "blur" }
        ],
        poId: [
          { required: true, message: "采购订单号不能为空", trigger: "blur" }
        ],
        itemId: [
          { required: true, message: "存货编码不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 计算合格和不合格数量
    calculateQuantities() {
      const actualQuantity = this.inspectForm.actualQuantity || 0;
      const totalRejection = this.inspectForm.rejectionRecords.reduce((total, record) => {
        return total + (record.rejectionQuantity || 0);
      }, 0);

      this.inspectForm.rejectQuantity = totalRejection;
      this.inspectForm.qualifiedQuantity = actualQuantity - totalRejection;
    },
    // 新增不合格记录
    handleAddRejection() {
      this.inspectForm.rejectionRecords.push({
        rejectionReason: '',
        rejectionQuantity: 1,
        handlingMethod: ''
      });
    },

    // 检验按钮操作
    handleInspect(row) {
      this.currentPlan = row;
      const ids = row.id || this.ids
      // this.resetInspectForm();
      console.log("检验按钮"+row.inspectForm);
      // 填充检验表单
      this.inspectForm.id = row.id;
      this.inspectForm.planId = row.planId;
      this.inspectForm.actualQuantity = row.actualQuantity || 0;
      this.inspectForm.qualifiedQuantity = row.qualifiedQuantity || 0;
      this.inspectForm.rejectQuantity = row.rejectQuantity || 0;
      this.inspectForm.inspector = row.inspector || '检验员王经理';
      this.inspectForm.inspectionResult = row.inspectionResult || 2;
      this.inspectForm.isRejected = row.isRejected || 2;
      this.inspectForm.remark = row.remark || '';

      // getPlan(ids).then(response => {
      //   this.form = response.data
      //   console.log("一条检验数据"+response.data);
      //   this.inspectForm.inspectionResults =response.data.inspectionItems;
      //
      // })

      /*加载检验项目数据（如果有检验方案）*/
        this.inspectForm.inspectionResults = row.inspectionResults.map(item => ({
          inspectionItemId: item.id,
          itemName: item.itemName,
          inspectionIndex: item.inspectionIndex,
          inspectionMethod: item.inspectionMethod,
          standardValue: item.standardValue,
          upperLimit: item.upperLimit,
          lowerLimit: item.lowerLimit,
          testValue1: '1',
          testValue2: '',
          testValue3: '',
          testValue4: '',
          testValue5: ''
        }));
      //
      // // 加载不合格记录（如果已存在）
      // if (row.rejectionRecords && row.rejectionRecords.length > 0) {
      //   this.inspectForm.rejectionRecords = [...row.rejectionRecords];
      // }

      this.inspectOpen = true;
    },
    /** 查询收料检验计划列表 */
    getList() {
      this.loading = true
      listPlan(this.queryParams).then(response => {
        console.log("页面"+response.rows)
        this.planList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        planId: null,
        receiveId: null,
        poId: null,
        itemId: null,
        batch: null,
        vendorId: null,
        inspectionStatus: null,
        inspector: null,
        inspectionResult: null,
        actualQuantity: null,
        rejectQuantity: null,
        qualifiedQuantity: null,
        isRejected: null,
        createdAt: null,
        createdPerson: null,
        updatedAt: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加收料检验计划"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getPlan(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改收料检验计划"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePlan(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addPlan(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除收料检验计划编号为"' + ids + '"的数据项？').then(function() {
        return delPlan(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('purchase/plan/export', {
        ...this.queryParams
      }, `plan_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
